package com.atguigu.juc02;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class MyAirCondition //资源类 = Field + Method
{
    private int num = 0;

    Lock lock = new ReentrantLock();

    Condition condition = lock.newCondition();


    //    public synchronized void increment() {
//        while (num != 0) {
//            try {
//                this.wait();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//        System.out.println(Thread.currentThread().getName() + "->" + (++num));
//        this.notifyAll();
//
//    }
//
//    public synchronized void decrement() {
//        while (num == 0) {
//            try {
//                this.wait();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//        System.out.println(Thread.currentThread().getName() + "->" + (--num));
//        this.notifyAll();
//
//    }
    public void increment() {


        lock.lock();
        try {
            while (num != 0) {
                condition.await();
            }
            System.out.println(Thread.currentThread().getName() + "->" + (++num));
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

    public void decrement() {

        lock.lock();
        try {
            while (num == 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "->" + (--num));
            condition.signalAll();
        } finally {
            lock.unlock();
        }


    }


}


/**
 * @auther zzyy
 * @create 2020-03-26 11:41
 * <p>
 * 有一个初始值为零的变量，现有两个线程对该变量操作，
 * 实现一个线程对变量加1，实现一个线程对变量减1,交替来10次
 * <p>
 * 1 高内聚低耦合的前提下，线程       操作    资源类
 * 2 判断、干活、通知
 * 3 防止线程的虚假唤醒，判断推荐使用while而不是单单的if判断
 */
public class ProdConsumerDemo2 {
    public static void main(String[] args) {
        MyAirCondition airCondition = new MyAirCondition();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                airCondition.increment();
            }
        }, "1").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                airCondition.decrement();
            }
        }, "2").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                airCondition.increment();
            }
        }, "3").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                airCondition.decrement();
            }
        }, "4").start();

    }
}
